package admin

import (
	"errors"
	"fmt"
	"gin_demo/models"
	"net/http"
	"time"

	"github.com/beego/beego/validation"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type AddUser struct {
	UserName   string `form:"user_name" json:"user_name" valid:"Required" binding:"required"`
	UserMobile string `form:"user_mobile" json:"user_mobile" valid:"Required" binding:"required"`
	OpenId     string `form:"open_id" json:"open_id" valid:"Required" binding:"required"`
}

func UserAdd(c *gin.Context) {

	var add_user AddUser
	// 将request的body中的数据，自动按照json格式解析到结构体
	if err := c.ShouldBindJSON(&add_user); err != nil {
		// 返回错误信息
		// gin.H封装了生成json数据的工具
		c.JSON(http.StatusBadRequest, gin.H{"error1": err.Error()})
		return
	}

	valid := validation.Validation{}
	b, err := valid.Valid(&add_user)
	if err != nil {
		// handle error
		fmt.Println(err.Error())
	}
	if !b {
		// validation does not pass
		// blabla...
		for _, err := range valid.Errors {
			c.JSON(http.StatusBadRequest, gin.H{"error2": fmt.Sprintf("%v", err.Message)})

			return
		}
	}

	user := models.User{
		UserName:   add_user.UserName,
		UserMobile: add_user.UserMobile,
		OpenId:     add_user.OpenId,
		CreateTime: int(time.Now().Unix()),
		UpdateTime: int(time.Now().Unix()),
	}

	result := models.GetSession().Create(&user)

	if result.Error != nil && !errors.Is(result.Error, gorm.ErrRecordNotFound) {
		c.JSON(http.StatusOK, gin.H{"msg": "失败 sql error", "code": 0, "data": ""})
		return
	}

	if result.Error != nil {
		c.JSON(http.StatusOK, gin.H{"msg": "失败", "code": 0})
	} else {
		c.JSON(http.StatusOK, gin.H{"msg": "成功", "code": 1})
	}

}

type GetUserIdData struct {
	Id int `form:"id" json:"id" valid:"Required" binding:"required"`
}

func GetUserId(c *gin.Context) {

	var param_data GetUserIdData
	// 将request的body中的数据，自动按照json格式解析到结构体
	if err := c.ShouldBindJSON(&param_data); err != nil {
		// 返回错误信息
		// gin.H封装了生成json数据的工具
		c.JSON(http.StatusBadRequest, gin.H{"error1": err.Error()})
		return
	}

	valid := validation.Validation{}
	b, err := valid.Valid(&param_data)
	if err != nil {
		// handle error
		fmt.Println(err.Error())
	}
	if !b {
		// validation does not pass
		// blabla...
		for _, err := range valid.Errors {
			c.JSON(http.StatusBadRequest, gin.H{"error2": fmt.Sprintf("%v", err.Message)})

			return
		}
	}

	user := models.User{}

	result := models.GetSession().Where("id = ?", param_data.Id).First(&user)

	if result.Error != nil && !errors.Is(result.Error, gorm.ErrRecordNotFound) {
		c.JSON(http.StatusOK, gin.H{"msg": "失败 sql error", "code": 0, "data": ""})
		return
	}

	if result.Error != nil {
		c.JSON(http.StatusOK, gin.H{"msg": "失败", "code": 0, "data": ""})
	} else {
		c.JSON(http.StatusOK, gin.H{"msg": "成功", "code": 1, "data": user})
	}

}

type UpdateUserIdData struct {
	Id         int    `form:"id" json:"id" valid:"Required" binding:"required"`
	UserName   string `form:"user_name" json:"user_name" valid:"Required" binding:"required"`
	UserMobile string `form:"user_mobile" json:"user_mobile" valid:"Required" binding:"required"`
}

func UpdateUserId(c *gin.Context) {

	var param_data UpdateUserIdData
	// 将request的body中的数据，自动按照json格式解析到结构体
	if err := c.ShouldBindJSON(&param_data); err != nil {
		// 返回错误信息
		// gin.H封装了生成json数据的工具
		c.JSON(http.StatusBadRequest, gin.H{"error1": err.Error()})
		return
	}

	valid := validation.Validation{}
	b, err := valid.Valid(&param_data)
	if err != nil {
		// handle error
		fmt.Println(err.Error())
	}
	if !b {
		// validation does not pass
		// blabla...
		for _, err := range valid.Errors {
			c.JSON(http.StatusBadRequest, gin.H{"error2": fmt.Sprintf("%v", err.Message)})

			return
		}
	}

	user := models.User{}

	result := models.GetSession().Where("id = ?", param_data.Id).First(&user)

	if result.Error != nil && !errors.Is(result.Error, gorm.ErrRecordNotFound) {
		c.JSON(http.StatusOK, gin.H{"msg": "失败 sql error", "code": 0, "data": ""})
		return
	}

	if result.RowsAffected == 0 {
		c.JSON(http.StatusOK, gin.H{"msg": "用户不存在", "code": 0, "data": ""})
		return
	}

	update_user := models.User{
		Id:         user.Id,
		UserName:   param_data.UserName,
		UserMobile: param_data.UserMobile,
		UpdateTime: int(time.Now().Unix()),
	}
	fmt.Println("user_id", user.Id, user.CreateTime)
	result = models.GetSession().Model(&user).Select("user_name", "user_mobile", "update_time").Updates(update_user)

	if result.Error != nil {
		c.JSON(http.StatusOK, gin.H{"msg": "失败", "code": 0, "data": ""})
	} else {
		c.JSON(http.StatusOK, gin.H{"msg": "成功", "code": 1, "data": ""})
	}

}

func DelUserId(c *gin.Context) {

	var param_data GetUserIdData
	// 将request的body中的数据，自动按照json格式解析到结构体
	if err := c.ShouldBindJSON(&param_data); err != nil {
		// 返回错误信息
		// gin.H封装了生成json数据的工具
		c.JSON(http.StatusBadRequest, gin.H{"error1": err.Error()})
		return
	}

	valid := validation.Validation{}
	b, err := valid.Valid(&param_data)
	if err != nil {
		// handle error
		fmt.Println(err.Error())
	}
	if !b {
		// validation does not pass
		// blabla...
		for _, err := range valid.Errors {
			c.JSON(http.StatusBadRequest, gin.H{"error2": fmt.Sprintf("%v", err.Message)})

			return
		}
	}

	user := models.User{}

	result := models.GetSession().Where("id = ?", param_data.Id).First(&user)

	if result.Error != nil && !errors.Is(result.Error, gorm.ErrRecordNotFound) {
		c.JSON(http.StatusOK, gin.H{"msg": "失败 sql error", "code": 0, "data": ""})
		return
	}

	if result.RowsAffected == 0 {
		c.JSON(http.StatusOK, gin.H{"msg": "用户不存在", "code": 0, "data": ""})
		return
	}

	result = models.GetSession().Delete(&user)

	if result.Error != nil {
		c.JSON(http.StatusOK, gin.H{"msg": "失败", "code": 0, "data": ""})
	} else {
		c.JSON(http.StatusOK, gin.H{"msg": "成功", "code": 1, "data": user})
	}

}

type GetUserAllData struct {
	PageNum  int    `form:"page_num" json:"page_num" valid:"Required"`
	IsFenye  int    `form:"is_fenye" json:"is_fenye" valid:"Range(0,1)"`
	PageSize int    `form:"page_size" json:"page_size" valid:"Required"`
	UserName string `form:"user_name" json:"user_name"`
	Status   int    `form:"status" json:"status" valid:"Range(0,2)"`
}

// 列表数据返回格式
type PageDataList struct {
	Count    int         `json:"count"`
	PageNum  int         `json:"page_num"`
	PageSize int         `json:"page_size"`
	Data     interface{} `json:"data"`
}

func A(c *gin.Context) {
	c.Set("name", "lijun")
	v, ok := c.Get("name")
	fmt.Println("A", v, ok)
	c.String(http.StatusOK, "设置成功")
}

func B(c *gin.Context) {
	v, ok := c.Get("name")
	fmt.Println("B", v, ok)
	c.String(http.StatusOK, "获取成功")
}
func GetAllUser(c *gin.Context) {

	var param_data GetUserAllData
	var qs = models.GetSession()
	// 将request的body中的数据，自动按照json格式解析到结构体
	if err := c.ShouldBindJSON(&param_data); err != nil {
		// 返回错误信息
		// gin.H封装了生成json数据的工具
		c.JSON(http.StatusBadRequest, gin.H{"error1": err.Error()})
		return
	}

	valid := validation.Validation{}
	b, err := valid.Valid(&param_data)
	if err != nil {
		// handle error
		fmt.Println(err.Error())
	}
	if !b {
		// validation does not pass
		// blabla...
		for _, err := range valid.Errors {
			c.JSON(http.StatusBadRequest, gin.H{"error2": fmt.Sprintf("%v", err.Message)})

			return
		}
	}

	users := []models.User{}
	all_users := []models.User{}

	if param_data.UserName != "" {
		qs = qs.Where("user_name LIKE ?", "%"+param_data.UserName+"%")
	}

	qs.Order("id DESC").Find(&all_users)
	if param_data.IsFenye == 1 {
		qs.Offset((param_data.PageNum - 1) * param_data.PageSize).Limit(param_data.PageSize).Order("id DESC").Find(&users)
	} else {
		qs.Order("id DESC").Find(&users)
	}

	res_data_json := PageDataList{
		Count:    len(all_users),
		PageNum:  param_data.PageNum,
		PageSize: param_data.PageSize,
		Data:     users,
	}

	c.JSON(http.StatusOK, gin.H{"msg": "成功", "code": 1, "data": res_data_json})

}
